package com.venutech.gongan.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class DevicesHttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(DevicesHttpUtil.class);

    public static final String GET = "GET";
    public static final String POST = "POST";
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;


    //一机一档里面的token
    static String  KEY="device_qimingtiangong";
    //一机一档里面的token
    static String deviceType="IPC";
    //一机一档
    public static String JUHE_YJYD_URL="http://32.90.18.97/kdall/devices/queryAll";

    //运维接口token
    public static String DEF_YJYD_TOKE="5B4F4DB4-9AB9-4EC9-9DB8-A5DF9334QMTG";
    //运维接口
    static String METHOD="GetFaultInfo";
    //运维信息拉取接口
    public static String  JUHE_KDALL_DEVICES_URL="http://172.22.28.154:8089/ashx/WebApi.ashx";

    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";


    /**
     * 一机一档接口
     * @return
     * @throws Exception
     */
    public static String devicesQuery(String startTime) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("key", KEY);
        paramMap.put("deviceType", deviceType);
        paramMap.put("f_in_status", 1+","+2+","+3);
        paramMap.put("startTime", startTime);
        paramMap.put("f_like_departmentCode", "320508");
        paramMap.put("paging","false");
        return DevicesHttpUtil.net(JUHE_YJYD_URL, paramMap, GET, "application/json");
    }
    /**
     * 一机一档接口查询所以数据
     * @return
     * @throws Exception
     */
    public static String devicesQueryList() throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("key", KEY);
        paramMap.put("deviceType", deviceType);
        paramMap.put("f_in_status", 1+","+2+","+3);
        paramMap.put("f_like_departmentCode", "320508");
        paramMap.put("f_eq_deviceAttr.ipc.monitorType", 1);
        paramMap.put("paging","false");
        return DevicesHttpUtil.net(JUHE_YJYD_URL, paramMap, GET,"application/json");
    }

    /**
     * 运维接口
     * @return
     * @throws Exception
     */
    public  static String getGetFaultInfo(String startTime) throws Exception {
        String urlString =null;
        logger.info("getGetFaultInfo:startTime={}",startTime);
        if(StringUtils.isNotEmpty(startTime)){
             urlString =JUHE_KDALL_DEVICES_URL+"?startTime="+startTime+"&Method="+METHOD+"&token="+DEF_YJYD_TOKE;
        }else{
            urlString =JUHE_KDALL_DEVICES_URL+"?Method="+METHOD+"&token="+DEF_YJYD_TOKE;
        }
        String res="";
        logger.info("getGetFaultInfo:urlString={}",urlString);
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type","application/json");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line+"\n";
            }
            in.close();
        } catch (Exception e) {
            System.out.println("error in wapaction,and e is " + e.getMessage());
        }
        return res;
    }

    /**
     * Get/Post请求方法
     *
     * @param strUrl 请求地址
     * @param paramMap 请求参数
     * @param method 请求方法
     * @return 网络请求字符串
     * @throws Exception
     */
    public static  String net(String strUrl, Map<String, ?> paramMap, String method, String userType) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals(GET)) {
                strUrl = strUrl + "?" + urlencode(paramMap);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals(GET)) {
                conn.setRequestMethod(GET);
            } else {
                conn.setRequestMethod(POST);
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("Content-Type", userType);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (paramMap != null && method.equals(POST)) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(paramMap));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            logger.error("DevicesHttpUtil.net : ex=", e);
        } finally {
            close(reader);
            close(conn);
        }
        return rs;
    }

    /**
     * 将Map型转为请求参数弄
     *
     * @param params
     * @return
     */
    private static String urlencode(Map<String, ?> params) {
        System.err.println(params);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : params.entrySet()) {
            try {
                String val = URLEncoder.encode(String.valueOf(i.getValue()), DEF_CHATSET);
                sb.append(i.getKey()).append("=").append(val).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String url=sb.substring(0,sb.lastIndexOf("&"));
        return url;
    }

    private static void close(BufferedReader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void close(HttpURLConnection conn) {
        if (conn != null) {
            conn.disconnect();
        }
    }


    public static StringBuffer interFaceUtile(String strUrl,Object data,String METHOD) throws Exception{
        StringBuffer sb=new StringBuffer();
        try {
            URL url=new URL(strUrl);
            HttpURLConnection conn =(HttpURLConnection)url.openConnection();
            PrintWriter out=null;
            conn.setRequestMethod(METHOD);
            conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setAllowUserInteraction(false);

            out=new PrintWriter(conn.getOutputStream());
            out.println(data);
            out.flush();
            out.close();
            InputStream is =conn.getInputStream();
            BufferedReader br =new BufferedReader(new InputStreamReader(is));
            String str="";
            while ((str=br.readLine()) !=null){
                sb.append(str);
            }
            is.close();
            conn.disconnect();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return sb;
    }



}

